﻿using System;
using System.Collections;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using BrnMall.Business;
using BrnMall.Core;
using BrnMall.Manager.Domain.Store;
using BrnMall.Manager.Manager.HaHaTool;
using BrnMall.Manager.Manager.Order;
using BrnMall.Manager.Manager.Product;
using BrnMall.Manager.Manager.Store;
using BrnMall.Manager.Manager.WeApp;
using BrnMall.Sdk.WeiXin.weapp;
using BrnMall.Services;
using WeiTap.Restful;

namespace BrnMall.Web.RestApi.Controllers
{
    /// <summary>
    /// 商城后台工具控制器类
    /// </summary>
    public class ToolController : WebApi
    {

        /// <summary>
        /// 上传
        /// </summary>
        /// 参数operation
        /// uploaduserreview 上传用户评价图片
        /// uploadusertimeline 上传用户图册
        /// <returns></returns>
        public string Upload()
        {
            string operation = WebHelper.GetQueryString("operation");
            if (HttpContext.Current.Request.Files.Count == 0)
                throw new Exception("未找到待上传的文件");

            if (operation == "uploaduserreview")//上传用户评价图片
            {
                var file = HttpContext.Current.Request.Files[0];
                var wrapper = new HttpPostedFileWrapper(file);
                string result = Uploads.SaveUploadUserReview(wrapper);
                return result;
            }
            if (operation == "uploadusertimeline")//上传用户图册
            {
                var file = HttpContext.Current.Request.Files[0];
                var wrapper = new HttpPostedFileWrapper(file);
                string result = Uploads.SaveUploadUserTimeLine(wrapper);
                return result;
            }
            if (operation.Equals("uploadwxpaycert"))//上传证书
            {
                var file = HttpContext.Current.Request.Files[0];
                var wrapper = new HttpPostedFileWrapper(file);
                var storeId = WebHelper.GetQueryString("storeid");

                var result = Uploads.SaveCertFile(Convert.ToInt32(storeId), wrapper);
                return result;
            }
            if (operation == "savecardavater")//上传名片头像
            {
                var file = HttpContext.Current.Request.Files[0];
                var wrapper = new HttpPostedFileWrapper(file);
                string result = Uploads.SaveUploadStoreCardAvater(wrapper);
                return result;
            }
            if (operation == "uploadblogimage")    //上传商圈图片
            {
                var file = HttpContext.Current.Request.Files[0];
                var wrapper = new HttpPostedFileWrapper(file);
                var storeId = WebHelper.GetQueryString("storeid");
                string result = Uploads.SaveUploadStoreBlogImage(Convert.ToInt32(storeId), wrapper);
                return result;
            }
            return string.Empty;
        }

        /// <summary>
        /// 省列表
        /// </summary>
        /// <returns></returns>
        public string ProvinceList()
        {
            List<RegionInfo> regionList = Regions.GetProvinceList();

            StringBuilder sb = new StringBuilder();

            sb.Append("[");

            foreach (RegionInfo info in regionList)
            {
                sb.AppendFormat("{0}\"id\":\"{1}\",\"name\":\"{2}\"{3},", "{", info.RegionId, info.Name, "}");
            }

            if (regionList.Count > 0)
                sb.Remove(sb.Length - 1, 1);

            sb.Append("]");

            return sb.ToString();
        }

        /// <summary>
        /// 市列表
        /// </summary>
        /// <param name="provinceId">省id</param>
        /// <returns></returns>
        public string CityList(int provinceId = -1)
        {
            List<RegionInfo> regionList = Regions.GetCityList(provinceId);

            StringBuilder sb = new StringBuilder();

            sb.Append("[");

            foreach (RegionInfo info in regionList)
            {
                sb.AppendFormat("{0}\"id\":\"{1}\",\"name\":\"{2}\"{3},", "{", info.RegionId, info.Name, "}");
            }

            if (regionList.Count > 0)
                sb.Remove(sb.Length - 1, 1);

            sb.Append("]");

            return sb.ToString();
        }

        /// <summary>
        /// 县或区列表
        /// </summary>
        /// <param name="cityId">市id</param>
        /// <returns></returns>
        public string CountyList(int cityId = -1)
        {
            List<RegionInfo> regionList = Regions.GetCountyList(cityId);

            StringBuilder sb = new StringBuilder();

            sb.Append("[");

            foreach (RegionInfo info in regionList)
            {
                sb.AppendFormat("{0}\"id\":\"{1}\",\"name\":\"{2}\"{3},", "{", info.RegionId, info.Name, "}");
            }

            if (regionList.Count > 0)
                sb.Remove(sb.Length - 1, 1);

            sb.Append("]");

            return sb.ToString();
        }
       
        /// <summary>
        /// 清除授权，针对某些客户不知道授权了哪个小程序
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public bool DeleteAuth(int storeAppId)
        {
            StoreApplicationManager.DeleteAuthorization(storeAppId);
            return true;
        }

        ///  <summary>
        /// 重置状态
        ///  </summary>
        ///  <param name="storeAppId"></param>
        /// <param name="devStatus">开发状态0:未知，1:待上传，2:已上传，3：待审核 4:审核结束，5:已发布</param>
        /// <returns></returns>
        public bool ResetStatus(int storeAppId,int devStatus)
        {
            var weapp = StoreApplicationManager.GetStoreApplication(storeAppId);
            weapp.DevStatus = devStatus;
            StoreApplicationManager.UpdateStoreApplication(weapp);
            return true;
        }
        /// <summary>
        /// 针对提示ext_json中有不存在的路径，重置底部导航设置
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public bool ResetTabBar(int storeAppId)
        {
            var storeApp = StoreApplicationManager.GetStoreApplication(storeAppId);
            if (storeApp == null) return false;
            var app = WeApplicationManager.GetWeApplication(storeApp.AppId);
            storeApp.DevStatus = 5;
            storeApp.UserTabBar = app.RawTabBar;
            StoreApplicationManager.UpdateStoreApplication(storeApp);
            return true;
        }
        /// <summary>
        /// 根据模板重置底部导航设置
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public bool InitTabBar(int storeAppId)
        {
            var storeApp = StoreApplicationManager.GetStoreApplication(storeAppId);
            if (storeApp == null) return false;
            var app = WeApplicationManager.GetWeApplication(storeApp.AppId);
            storeApp.UserTabBar = app.RawTabBar;
            StoreApplicationManager.UpdateStoreApplication(storeApp);
            return true;
        }
        /// <summary>
        /// 解决分销商信息重复问题
        /// </summary>
        /// <param name="storeId">店铺编号</param>
        /// <returns></returns>
        public bool ClearDistributor(int storeId)
        {
            if (storeId <= 0) return false;
            ToolManager.ClearDuplicateDistributor(storeId);
            return true;
        }

        
        /// <summary>
        /// 发送用户支付成功通知
        /// </summary>
        /// <param name="oid"></param>

        public void SendUserPaySuccessMessage(int oid)
        {
            Orders.SendPaySuccessMessage(oid);
        }
        /// <summary>
        /// 发送用户发货成功成功通知
        /// </summary>
        /// <param name="oid"></param>
        public void SendUserDeliverSuccessMessage(int oid)
        {
            Orders.SendDeliverSuccessMessage(oid);
        }
        /// <summary>
        /// 发送店铺订单成功支付消息
        /// </summary>
        /// <param name="oid"></param>
        public void SendStoreOrderPaySuccessMessage(int oid)
        {
            Orders.SendStoreOrderPaySuccessMessage(oid);
        }
        /// <summary>
        /// 发送店铺成功下单消息
        /// </summary>
        /// <param name="oid"></param>
        public void SendStoreCreateOrderSuccessMessage(int oid)
        {
            Orders.SendStoreCreateOrderSuccessMessage(oid);
        }
        /// <summary>
        /// 发送店铺订单收货通知
        /// </summary>
        /// <param name="oid"></param>
        public void SendStoreOrderRecieveMessage(int oid)
        {
            Orders.SendStoreOrderRecieveMessage(oid);
        }
        /// <summary>
        /// 发送店铺预约待处理通知
        /// </summary>
        /// <param name="aid"></param>
        public void SendStoreAppointAddMessage(int aid)
        {
            Orders.SendStoreAppointAddMessage(aid);
        }
        /// <summary>
        /// 获取小程序的第三方提交代码的页面配置
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public Pages GetTempatePages(int storeAppId)
        {
            return StoreAppReleaseManager.GetTempatePages(storeAppId);
        }
        

        /// <summary>
        /// 更新店铺产品销量不对的情况
        /// </summary>
        /// <param name="storeId"></param>
        public void CaculateRealSaleCount(int storeId)
        {
            var condition = AdminProducts.AdminGetProductListCondition(storeId, 0, "", 0, 0, 0);
            var products = AdminProducts.AdminGetProductList(1000, 1, condition);
            IDictionary<int,int> pidSale=new Dictionary<int, int>();
            foreach (DataRow pRow in products.Rows)
            {
                var pid = TypeHelper.ObjectToInt(pRow["pid"]);
                var realCount = ProductManager.CaculateRealSaleCount(pid);
                pidSale.Add(pid,realCount);
            }
            ProductManager.UpdateRealSaleCount(pidSale);

        }

        /// <summary>
        /// 添加区域
        /// </summary>
        /// <param name="province">省份</param>
        /// <param name="city">市</param>
        /// <param name="county">区</param>
        /// <returns></returns>
        public bool AddRegion(string province, string city, string county)
        {
            if (string.IsNullOrEmpty(province) ||
                string.IsNullOrEmpty(city) ||
                string.IsNullOrEmpty(county))
                throw new Exception("参数不能为空");
            var pr = Regions.GetRegionByNameAndLayer(province, 1);
            if (pr == null)
                throw new Exception("未找到相关的省份");
            var cr = Regions.GetRegionByNameAndLayer(city, 2);
            if (cr == null)
                throw new Exception("未找到相关的城市");
            var ctry = Regions.GetRegionByNameAndLayer(county, 3);
            if (ctry != null)
                throw new Exception("区域已经存在");
            var newCountry = new Region
            {
                CityId = cr.RegionId,
                CityName = cr.Name,
                DisplayOrder = 0,
                Layer = 3,
                Name = county,
                ParentId = cr.RegionId,
                ProvinceId = cr.ProvinceId,
                ShortSpell = string.Empty,
                Spell = string.Empty
            };
            return RegionManager.AddRegion(newCountry);
        }

    }
}
